import QtQuick 2.6
import QtQuick.Controls 1.1
import QtQuick.Layouts 1.1
import QtQuick.LocalStorage 2.0
import QtQuick.Window 2.2
import "qrc:/PageView/"


Window {

    property var localdb
    visible: true
    width: 1024
    height: 600
    title: qsTr("QML&JS&SQlite")

    // 弹出层
    Popup {
        MouseArea {
            x: 0
            y: 150
            width: 200
            height: 200




            onClicked: {

                updateDBData(popup.oldname,idName.text,idnum.text);
                view.model.clear();
                getDBData(view.model);
                parent.hide()
            }
        }
        id: popup
        property string oldname:idName.text;

        width: 200; height: 180
        anchors.centerIn: parent
        z: 101
        opacity: 0.8
        visible: false;
        radius: 5

        //
        //            Text{
        //                text: 'this is popop'
        //                anchors.bottom: parent.bottom
        //                anchors.centerIn: parent
        //            }
        Button {
            id: btnClose
            anchors.horizontalCenter: parent.horizontalCenter
            anchors.bottom: parent.bottom
            anchors.bottomMargin: 10
            text:"修改"
            width: 98

            onClicked: {

                updateDBData(popup.oldname,idName.text,idnum.text);
                view.model.clear();

                getDBData(view.model);
                btnClose.text="修改成功！"
//                parent
            }
        }

        Label {
            id: label1
            x: 0
            y: 33
            width: 101
            height: 21
            text: "姓名"
            verticalAlignment: Text.AlignVCenter
            horizontalAlignment: Text.AlignHCenter
            wrapMode: Text.WordWrap
        }

        Label {
            id: label2
            x: 0
            y: 73
            width: 101
            height: 21
            text: "学号"
            wrapMode: Text.WordWrap
            verticalAlignment: Text.AlignVCenter
            horizontalAlignment: Text.AlignHCenter
        }


        TextField {
            id: idName
            width: 100;
            x: 75
            y: 30
            placeholderText: qsTr("")
        }

        TextField {
            id: idnum
            width: 100;
            x: 75
            y: 70
            placeholderText: qsTr("")

        }
        Timer {
            id: timer_button;
            interval: 1000;//设置定时器定时时间为500ms,默认1000ms
            repeat: false //是否重复定时,默认为false
            running: false //是否开启定时，默认是false，当为true的时候，进入此界面就开始定时
            triggeredOnStart: false // 是否开启定时就触发onTriggered，一些特殊用户可以用来设置初始值。
            onTriggered: {button1.text="添加新项"  //定时触发槽,定时完成一次就进入一次
            }
            //restart ,start,stop,定时器的调用方式，顾名思义


        }

        Button {
            id: button1
            anchors.horizontalCenter: parent.horizontalCenter
            anchors.bottom: parent.bottom
            anchors.bottomMargin: 42
            text:"添加新项"
            width: 98

            onClicked:
            {

                if((idName.text.length>0)&&(idnum.text.length))
                {
                    insertDBData(idName.text,idnum.text);
                    //     view.model.append({"index":idnum.text,"content":idName.text});
                    button1.text="添加成功！";
                    timer_button.restart();

                }
                else
                {
                    console.log("cann't empty");
                }
            }
        }
    }



    ListViewEx{
        id: view
        anchors.fill: parent
        pageSize: 50
        snapHeader: true
        initPosition: 'first'

        // 顶部新闻图片栏
        headerComponent: Component{
            Rectangle{
                width: view.width
                height: 40
                color: '#f0f0f0'

                Rectangle{
                    anchors.left: parent.left
                    anchors.right: parent.right
                    anchors.leftMargin: 5
                    anchors.rightMargin: 5
                    anchors.verticalCenter: parent.verticalCenter
                    border.color: '#d0d0d0'
                    border.width: 1
                    height: 24
                    radius: height/2
                    TextInput{

                        id:searchtext
                        x: 5
                        text: '请输入查询名字'
                        anchors.left: parent.left
                        anchors.leftMargin: 15
                        anchors.verticalCenter: parent.verticalCenter
                        color: '#b0b0b0'
                        selectByMouse: true
                        onAccepted:
                            searchDBData(view.model,searchtext.text);
                        //                        MouseArea {
                        //                            anchors.fill: parent;
                        //                            onClicked: {

                        //                                searchtext.selectAll();

                        //                            }
                        //                        }

                    }

                    Text{
                        x: 5
                        text: 'Q'
                        anchors.right: parent.right
                        anchors.rightMargin: 8
                        anchors.verticalCenter: parent.verticalCenter
                        color: '#b0b0b0'
                        MouseArea {
                            anchors.fill: parent;
                            onClicked: {

                                searchDBData(view.model,searchtext.text);


                            }
                        }
                    }
                }
            }
        }

        // 行UI代理

        delegate:Flickable {

            width: view.width; height: 32
            contentWidth: parent.width*1.4; contentHeight: 32
            boundsBehavior:Flickable.StopAtBounds //该属性设置过后，边界不会被拉出
            Text {
                id: wrapper;
                width: parent.width;
                height: 32;
                font.pointSize: 15;
                verticalAlignment: Text.AlignVCenter;
                horizontalAlignment: Text.AlignHCenter;
                transform: Translate{ x: -view.width*0.2 }

                text: content;
                //color: ListView.view.currentIndex == index ? "white" : "#505050";
                MouseArea {
                    anchors.fill: parent;
                    onClicked:  view.currentIndex=index;
                    onDoubleClicked:{
                        oldname:idName.text;
                        popup.animationType = 'size';
                        popup.show();
                        var na=(view.model.get(index).content).replace(/\s/g, "");
                        idName.text=na;
                        getnumDBData(view.model,na,idnum);
                        btnClose.text="修改"
                        //                        idnum.text=nu;
                    }
                }

            }
            Rectangle{
                id: testbtn
                height: parent.height
                width: parent.width*0.28
                color: "red"
                anchors.right: parent.right
                Text {
                    anchors.centerIn: parent
                    text: qsTr("删除")
                    color: "#ffffff"
                }

                MouseArea{
                    anchors.fill: parent
                    onClicked: {
                        //去除空格执行删除操作
                        var na=(view.model.get(index).content).replace(/\s/g, "");
                        console.log(na);
                        deleteDBData(na);
                        view.model.clear();
                        getDBData(view.model);


                    }
                }
            }



        }


        // 高亮
        highlight: Rectangle {
            width: view.width
            color: "steelblue";
            opacity: 0.5
        }



        //-----------------------------------------
        // 数据加载事件
        //-----------------------------------------
        onLoad:{
            openDB();
            getDBData(model);

            //            for (var i = 0 ; i < pageSize ; ++i)
            //                model.append({"index": i, "content": "Item " + i})
        }
        onLoadMore:{

            //            for (var i = pageSize*page ; i < pageSize*(page+1); ++i)
            //                model.append({"index": i, "content": "Item " + i})
        }
    }

    ///////////////////////数据库操作/////////////////////

    //打开数据库，没有则创建，没有指定表则创建
    function  openDB()
    {
        localdb = LocalStorage.openDatabaseSync("QQmlValueRecordDB", "1.0", "QML LocalStorage", 1000000);

        localdb.transaction(function(tx){

            tx.executeSql('CREATE TABLE IF NOT EXISTS datasheet(name TEXT, num TEXT)');
        })
    }

    //数据库插入数据
    function insertDBData(name,num)
    {
        openDB();
        localdb.transaction(function(tx)
        {
            tx.executeSql('INSERT INTO datasheet VALUES(?,?)', [name,num]);
        })

    }

    //数据库删除数据
    function deleteDBData(name)
    {
        openDB();
        localdb.transaction(function(tx)
        {
            tx.executeSql('DELETE FROM datasheet WHERE name = (?)', [name]);
        })

    }

    //数据库修改数据
    function updateDBData(nameold,namenew,numnew)
    {
        openDB();
        localdb.transaction(function(tx)
        {
            console.log("修改数据库:"+namenew+"  "+numnew);

            tx.executeSql('UPDATE datasheet SET num == (?) WHERE name == (?);', [numnew,nameold]);
            tx.executeSql('UPDATE datasheet SET name == (?) WHERE num == (?);', [namenew,numnew]);
        })

    }

    //从数据库获取数据
    function getDBData(model)
    {
        openDB();
        //        var a=21;
        //        for(a=21;a<40;a++)
        //            insertDBData("黄凯"+a,String(a));
        localdb.transaction(function(tx)
        {
            var rs = tx.executeSql('SELECT * FROM datasheet');
            console.log(rs.rows.length);

            for (var i = 0 ; i < rs.rows.length ; ++i)
            {
                model.append({"index": i, "content": " "+rs.rows.item(i).name}); //加入到列表
            }
            //        for(var i = 0; i < rs.rows.length; i++)
            //        {
            //            model.append({"content":rs.rows.item(i).name,"index":rs.rows.item(i).num});
            //        }

        })

    }
    //从数据库查找数据

    function searchDBData(model,name)
    {
        openDB();
        localdb.transaction(function(tx)
        {
            var rs = tx.executeSql('SELECT * FROM datasheet  WHERE name GLOB \'*'+name+'*\';');
            console.log(rs.rows.length);
            model.clear();
            for (var i = 0 ; i < rs.rows.length ; ++i)
            {
                model.append({"index": i, "content": ""+rs.rows.item(i).name}); //加入到列表
            }

        })

    }
    //从数据库获取学号
    function getnumDBData(model,name,idnum){
        openDB();
        localdb.transaction(function(tx){

            var rs = tx.executeSql('SELECT * FROM datasheet WHERE name == (?)', [name]);
            console.log(rs.rows.item(0).num);
            idnum.text=rs.rows.item(0).num;


        })

    }

}





